package com.wy.controller;

import cn.hutool.core.io.FileUtil;
import com.sun.deploy.net.URLEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author 33117
 * @version 1.0
 * @data 2025/2/27 17:55
 */
@RestController
@RequestMapping("files")
public class FileController {
    // 获取当前项目的根路径
    private static final String filePath = System.getProperty("user.dir")+"/files/";

    /*
     *  文件上传
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file){
        // 获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 如果目录不存在，需要先创建目录
        if (!FileUtil.isDirectory(filePath)){
            FileUtil.mkdir(filePath);
        }
        // 给文件 加一个唯一标识
        String fileName = System.currentTimeMillis() + "_" + originalFilename;
        // 完整文件路径
        String reutFileName =filePath + fileName;
        try {
            FileUtil.writeBytes(file.getBytes(), reutFileName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        // 返回网络路径
        String url = "localhost:8080/files/download/"+reutFileName;
        return url;
    }

    /*
     * 文件下载
     */
    @GetMapping("download/{fileName}")
    public void download(@PathVariable("fileName")String name, HttpServletResponse response){
        try {
            // 响应头
            response.addHeader("Content-Disposition","attachment:filename="+ URLEncoder.encode(name, StandardCharsets.UTF_8.toString()));
            response.setContentType("application/octet-stream");
            OutputStream os = response.getOutputStream();
            // 获取文件的字节数据
            String fileName = filePath+ name;
            byte[] bytes = FileUtil.readBytes(fileName);
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
